﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace XYS.Core.Util
{
    /// <summary>
    /// 扩展
    /// </summary>
    public static partial class Extention
    {
        /// <summary>
        /// DataTable 转 实体集合
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="table"></param>
        /// <returns></returns>
        public static List<TResult> ToList<TResult>(this DataTable table)
            where TResult : class, new()
        {
            List<TResult> result = new();
            foreach (var row in table.Rows)
            {
                if (row is DataRow dataRow)
                    result.Add(dataRow.ToObject<TResult>());
            }
            return result;
        }

        /// <summary>
        /// DataRow 转 实体
        /// </summary>
        public static TResult ToObject<TResult>(this DataRow row)
            where TResult : class, new()
        {
            TResult model = null;
            if (row != null)
            {
                model = new();
                var properties = model.GetType().GetProperties();

                for (int i = 0; i < row.Table.Columns.Count; i++)
                {
                    var col = row.Table.Columns[i];
                    PropertyInfo proInfo = properties.FirstOrDefault(e => e.Name.ToLower() == col.ColumnName.ToLower());
                    if (proInfo != null && row[i] != DBNull.Value)
                    {
                        proInfo.SetValue(model, row[i], null);
                    }
                }
            }
            return model;
        }

    }
}
